package com.xayy.health.mgt.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.kawins.base.result.CheckResult;
import cn.kawins.base.utils.BeanUtil;
import cn.kawins.base.utils.CollUtil;
import cn.kawins.base.utils.HttpUtil;
import cn.kawins.mybatis.base.BaseServiceImpl;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.xayy.health.core.config.param.ExternalParam;
import com.xayy.health.core.utils.ConvertUtils;
import com.xayy.health.core.utils.TreeUtils;
import com.xayy.health.mgt.mapper.SatelliteMapper;
import com.xayy.health.mgt.mapper.TaskChildInfoMapper;
import com.xayy.health.mgt.mapper.TaskInfoMapper;
import com.xayy.health.mgt.model.*;
import com.xayy.health.mgt.model.vo.SatelliteTreeVo;
import com.xayy.health.mgt.model.vo.SubtaskDetailVo;
import com.xayy.health.mgt.model.vo.SubtaskPageParam;
import com.xayy.health.mgt.model.vo.tupu.*;
import com.xayy.health.mgt.service.SatelliteCodeService;
import com.xayy.health.mgt.service.SatelliteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangxa
 */
@Service
@SuppressWarnings(value = "all")
public class SatelliteServiceImpl extends BaseServiceImpl<Satellite> implements SatelliteService {

    @Resource
    private SatelliteMapper satelliteMapper;
    @Autowired
    private ExternalParam externalParam;
    @Autowired
    private TaskInfoMapper taskInfoMapper;
    @Autowired
    private TaskChildInfoMapper taskChildInfoMapper;
    @Autowired
    private SatelliteCodeService satelliteCodeService;

    /**
     * 查询节点树
     *
     * @return 结果日志
     */
    @Override
    public List<SatelliteTreeVo> selectTree() {
        List<Satellite> satellites = satelliteMapper.selectTree();
        List<SatelliteTreeVo> satelliteTreeVos = ConvertUtils.sourceToTarget(satellites, SatelliteTreeVo.class);
        return TreeUtils.build(satelliteTreeVos);
    }

    /**
     * 获取左侧树
     *
     * @return 左侧树信息
     */
    @Override
    public List<SatelliteTreeVo> selectLeftTree() {
        List<Satellite> satellites = satelliteMapper.selectLeftTree();
        List<SatelliteTreeVo> satelliteTreeVos = ConvertUtils.sourceToTarget(satellites, SatelliteTreeVo.class);
        return TreeUtils.build(satelliteTreeVos);
    }

    /**
     * 判断节点是否有子节点
     *
     * @param id 节点id
     * @return 日志信息
     */
    @Override
    public boolean hasChild(Long id) {
        int result = satelliteMapper.hasChild(id);
        return result > 0;
    }

    /**
     * 获取参数信息
     * @param satId 卫星id
     * @param nodeId 节点id
     * @return 结果日志
     */
    @Override
    public CheckResult<List<PropertiesVo>> getProperties(Long satId, Long nodeId) {
        List<PropertiesVo> propertiesVos = new ArrayList<>();
        // 调用第三方接口获取参数
        Map<String, Object> map = new HashMap<>();
        map.put("filterFlag", false);
        map.put("id", nodeId);
        map.put("labelName", "设备");
        HttpResponse getResponse = HttpUtil.createRequest(Method.GET, externalParam.getComArgUrl()).form(map).execute();
        if (getResponse.getStatus() != 200) {
            log.error("调用设备-参数信息获取接口异常");
            return CheckResult.fail("调用设备-参数信息获取接口异常");
        }
        Object data = JSON.parseObject(getResponse.body()).get("data");
        if (BeanUtil.isEmpty(data)) {
            return CheckResult.success(CollUtil.newArrayList());
        }
        EquipmentResponseVo responseVo = JSON.parseObject(data.toString(), EquipmentResponseVo.class);
        List<NodeVo> nodes = responseVo.getNodes();
        nodes.forEach(x -> {
            if ("设备".equals(x.getLabel()) || BeanUtil.isEmpty(x.getId())) {
                return;
            }
            PropertiesVo propertiesVo = new PropertiesVo();
            propertiesVo.setId(Long.valueOf(x.getId()));
            propertiesVo.setName(x.getProperties().getName());
            propertiesVo.setCode(x.getProperties().getCsdh());
            propertiesVo.setSatId(satId);
            propertiesVos.add(propertiesVo);
        });
        return CheckResult.success(propertiesVos);
    }

    /**
     * 获取节点树左侧信第三方接口
     * @param pageNum  页码
     * @param pageSize 页数
     * @param xingType 卫星类型
     * @return 结果日志
     */
    @Override
    public CheckResult<?> getLeftTreeByOther(Integer pageNum, Integer pageSize, String xingType) {

        if (Boolean.TRUE.equals(externalParam.ourOrotherApi)) {
            List<SatelliteNode> list = new ArrayList<>();
            if (xingType.equals("TongXin")) {
                SatelliteNode satelliteNode = new SatelliteNode();
                satelliteNode.setId(11034L);
                satelliteNode.setSatelliteId(11034L);
                satelliteNode.setSatelliteNewId("11034");
                satelliteNode.setName("XXXX04星");
                satelliteNode.setCode("TL104");
                satelliteNode.setXing("XXXX04星");
                list.add(satelliteNode);
            }
            if (xingType.equals("ZhongJi")) {
                SatelliteNode satelliteNode = new SatelliteNode();
                satelliteNode.setId(11035L);
                satelliteNode.setSatelliteId(11035L);
                satelliteNode.setSatelliteNewId("11035");
                satelliteNode.setName("XXXX01");
                satelliteNode.setCode("ST203");
                satelliteNode.setXing("XXXX01星");
                list.add(satelliteNode);
            }
            return CheckResult.success(list);
        } else {
            List<SatelliteNode> satelliteNodes = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            map.put("pageNum", pageNum);
            map.put("pageSize", pageSize);
            map.put("xingType", xingType);
            HttpResponse getResponse =
                    HttpUtil.createRequest(Method.GET, externalParam.getSatelliteUrl()).form(map).execute();
            if (getResponse.getStatus() != 200) {
                log.error("获取卫星信息列表接口异常");
                return CheckResult.fail("获取卫星信息列表接口异常");
            }
            Object data = JSON.parseObject(getResponse.body()).get("data");
            SatelliteApiVo satelliteApiVo = JSON.parseObject(data.toString(), SatelliteApiVo.class);
            List<SatelliteInfoVo> records = satelliteApiVo.getRecords();
            records.forEach(x -> {
                if (BeanUtil.isEmpty(x.getGraphId())) {
                    return;
                }
                SatelliteNode satelliteNode = new SatelliteNode();
                satelliteNode.setId(Long.valueOf(x.getGraphId()));
                satelliteNode.setSatelliteId(Long.valueOf(x.getGraphId()));
                satelliteNode.setSatelliteNewId(x.getSatelliteId());
                satelliteNode.setName(x.getXing());
                satelliteNode.setCode(x.getCode());
                satelliteNode.setXing(x.getXing());
                satelliteNodes.add(satelliteNode);
            });

            this.updateSatelliteId(satelliteNodes);
            return CheckResult.success(satelliteNodes);
        }
    }

    /**
     * 兼容卫星代号和卫星id（获取第三方卫星结构时，同步修改本地卫星id）
     *
     * @param satelliteNodes
     */
    public void updateSatelliteId(List<SatelliteNode> satelliteNodes) {
//        int i = 1;
//        if (i == 1) {
//            String sql = "delete from satellite_code";
//            satelliteMapper.cleanSatelliteCodeData(sql);
//            i++;
//        }
      //  List<SatelliteCode> satelliteCodes = satelliteCodeService.selectAll();
        if (!CollUtil.isEmpty(satelliteNodes)) {
            ArrayList<SatelliteCode> satelliteCodeArrayList = new ArrayList<>();
            for (SatelliteNode node : satelliteNodes) {
                String sql = "delete from satellite_code where satellite_new_id="+"\""+node.getSatelliteNewId()+"\"";
                satelliteMapper.cleanSatelliteCodeData(sql);
                SatelliteCode satelliteCode = new SatelliteCode();
                satelliteCode.setSatelliteId(node.getSatelliteId().toString());
                satelliteCode.setSatelliteName(node.getName());
                satelliteCode.setSatelliteCode(node.getCode());
                satelliteCode.setSatelliteNewId(node.getSatelliteNewId());
                satelliteCodeArrayList.add(satelliteCode);
            }
            satelliteCodeService.insertList(satelliteCodeArrayList);
        }
    }

    /**
     * 子任务详请展示
     * @param subtaskPageParam 子任务信息
     * @return 结果日志
     */
    @Override
    public CheckResult<?> subTaskDetail(SubtaskPageParam subtaskPageParam) {
        ArrayList<SubtaskDetailVo> finalList = new ArrayList<>();
        // 1.获取到1级节点数据
        PageMethod.startPage(subtaskPageParam.getPage(), subtaskPageParam.getSize());
        PageInfo<TaskInfo> taskInfoPageInfo = null;
        List<TaskInfo> taskInfosList = null;
        Example example = new Example(TaskInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("type", subtaskPageParam.getType());
        if (StrUtil.isNotEmpty(subtaskPageParam.getName()) && !"".equals(subtaskPageParam.getName())) {
            criteria.andLike("name", "%" + subtaskPageParam.getName() + "%");
        }
        taskInfosList = taskInfoMapper.selectByExample(example);
        taskInfoPageInfo = new PageInfo<>(taskInfosList);

        int pages = taskInfoPageInfo.getPages();
        int pageSize = taskInfoPageInfo.getPageSize();
        long total = taskInfoPageInfo.getTotal();
        if (CollUtil.isNotEmpty(taskInfosList)) {
            for (TaskInfo taskInfo : taskInfosList) {
                SubtaskDetailVo detailVo = SubtaskDetailVo.builder().id(taskInfo.getId()).pages(pages)
                        .pageSize(pageSize).total(total).name(taskInfo.getName()).startTime(taskInfo.getStartTime())
                        .status(taskInfo.getStatus()).endTime(taskInfo.getEndTime()).cycle(Integer.valueOf(taskInfo.getCycle()))
                        .tyTag(taskInfo.getTyTag()).tcTag(taskInfo.getTcTag()).phTag(taskInfo.getPhTag()).build();
                // 2.获取到2级节点数据
                List<TaskChildInfo> taskChildInfos = null;
                Example example1 = new Example(TaskChildInfo.class);
                Example.Criteria criteria1 = example1.createCriteria();
                criteria1.andEqualTo("taskId", taskInfo.getId());
                if (StrUtil.isNotEmpty(subtaskPageParam.getChildrenName()) && !"".equals(subtaskPageParam.getChildrenName())) {
                    criteria1.andLike("name", "%" + subtaskPageParam.getChildrenName() + "%");
                }
                taskChildInfos = taskChildInfoMapper.selectByExample(example1);
                detailVo.setChildren(taskChildInfos);
                finalList.add(detailVo);
            }
        }

        return CheckResult.success(finalList);
    }


}
